<template>
  <div>
    <!-- 按钮区 -->
    <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col>
        <el-upload
          :before-upload="beforeUpload"
          :show-file-list="false"
          accept=".xlsx,.xls,.csv"
        >
          <el-button type="primary">导入文件</el-button>
        </el-upload>
        <el-button type="success" @click="submitData" style="margin-left:10px">提交数据</el-button>
      </el-col>
    </el-row>

    <div style="width: 100%; overflow-x: auto;">
      <el-table
      :data="tableDataList.list"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
    <el-table-column prop="venderId" label="供应商编码" width="100" />
    <el-table-column prop="hnyyPurTypeName" label="政策类型" width="100"/>

    <el-table-column prop="hnyyPurRebateFromTypeName" label="取值来源" width="100"/>

    <el-table-column prop="startDate" label="协议起始期" width="100" :formatter="formatDate" />
    <el-table-column prop="endDate" label="协议结束期" width="100" :formatter="formatDate" />
    <el-table-column prop="hnyyRebateModueIdName" label="折让计算期间" width="100"/>

    <el-table-column prop="hnyyRebateMethdIdName" label="折让方式" width="100"/>

    <el-table-column prop="hnyyRebateTypeIdName" label="采购折让类型" width="100"/>

    <el-table-column prop="zbPrice" label="中标价" width="100" />
    <el-table-column prop="purPrice" label="进价" width="100" />
    <el-table-column prop="goodsRate" label="品种税率" width="100" />
    <el-table-column prop="clientId" label="客户id" width="100" />
    <el-table-column prop="sysClientPriceSetsList" label="客户集合" width="100" />
    <el-table-column prop="purRate" label="采购折让比率" width="100" />
    <el-table-column prop="purRebatePrice" label="采购折让单价" width="100" />
    <el-table-column prop="payDay" label="付款账期（天数）" width="100" />
    <el-table-column prop="comGoodsId" label="商品编码" width="100" />
    <el-table-column label="操作" width="100px">
      <template #default="scope">
        <el-button @click="deleteRow(scope.row)" type="danger">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination
          v-model:current-page="tableDataList.pageNum"
          v-model:page-size="tableDataList.pageSize"
          layout="total,sizes, prev, pager, next"
          :total="tableDataList.total"
          :page-sizes="[20, 40, 80]"
          @current-change="load"
          @size-change="load"
      />
  </div>
</template>


<script setup>
import { ref,reactive } from 'vue'
import * as XLSX from 'xlsx'
import request from '@/utils/request'
import { ElMessage } from 'element-plus';
import dayjs from "dayjs";

const tableData = ref([])
const columns = ref([])
// 政策维护数据
const policyForm=reactive({
  hnyyPurRebateListId: '',
  hnyyPurType: '',
  hnyyPurRebateFromType: '',
  venderId: '',
  startDate: '',
  endDate: '',
  hnyyRebateModueId: '',
  hnyyRebateMethdId:'',
  hnyyRebateTypeId:'',
  comGoodsId:'',
  goodsRate:'',
  zbPrice:'',
  purPrice:'',
  clientId:'',
  sysClientPriceSetsList:'',
  purRate:'',
  purRebatePrice:'',
  payDay:'',
  opFlag:'0',
  creater:'',
  createDate:'',
  checker:'',
  checkDate:'',
  statue:0,
  vender:{
    venderName:'',
    goodsInfo:'',
    venderCode:'',
    productLocation:''
  },
  // 其他字段
 other:{
  hnyyPurTypeName:'',
  hnyyPurRebateFromTypeName:'',
  hnyyRebateModueIdName:'',
  hnyyRebateMethdIdName:'',
  hnyyRebateTypeIdName:''
 }
})

const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}


// 解析上传文件
const beforeUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = e.target.result
    const workbook = XLSX.read(data, { type: 'binary', cellDates: false })
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]

    const sheetData = XLSX.utils.sheet_to_json(sheet, {
      header: 1,
      defval: "",
      blankrows: false
    })

    if (sheetData.length === 0) return
    const headers = sheetData[0]

    const rows = sheetData.slice(1)
      .filter(row => Array.isArray(row) && row.some(cell => {
        const value = String(cell ?? "").trim()
        return value !== "" && value.toLowerCase() !== "undefined" && value.toLowerCase() !== "null"
      }))
      .map(row => {
        const obj = {}
        headers.forEach((key, i) => {
          obj[key] = (row[i] ?? "").toString().trim()
        })
        return obj
      })

    // 再过滤一次，保证没空行
    tableData.value = rows.filter(row => Object.values(row).some(v => v !== ""))
    columns.value = headers



    // 处理日期
    rows.forEach(row => {
      if (typeof row["协议起始期"] === "number") {
        const date = XLSX.SSF.parse_date_code(row["协议起始期"])
        row["协议起始期"] = `${date.y}-${String(date.m).padStart(2,"0")}-${String(date.d).padStart(2,"0")}`
      }
      if (typeof row["协议结束期"] === "number") {
        const date = XLSX.SSF.parse_date_code(row["协议结束期"])
        row["协议结束期"] = `${date.y}-${String(date.m).padStart(2,"0")}-${String(date.d).padStart(2,"0")}`
      }
    })

    tableData.value = rows
    columns.value = headers

    // 存入数据库
     for (const row of tableData.value) {
    try {
      console.log("row['供应商编码']====>",row['供应商编码'])
      importSearch.value.venderName=row['供应商编码']
      importSearch.value.goodsName=row['商品编码']
      request.post('/link/getImport', importSearch.value).then(async (res)=>{
        console.log('res',row['商品编码'])
        if(res.code===200){
          Object.assign(policyForm, res.data)
          policyForm.comGoodsId=row['商品编码']
          policyForm.endDate=row['协议结束期']
          policyForm.startDate=row['协议起始期']
          policyForm.goodsRate=row['品种税率']
          policyForm.hnyyPurRebateFromType=sourceTypeMap[row['取值来源']]
          policyForm.other.hnyyPurRebateFromTypeName=row['取值来源']
          policyForm.hnyyPurType=policyTypeMap[row['政策类型']]
          policyForm.other.hnyyPurTypeName=row['政策类型']
          policyForm.hnyyRebateMethdId=rebateMethodTypeMap[row['折让方式']]
          policyForm.other.hnyyRebateMethdIdName=row['折让方式']
          policyForm.hnyyRebateTypeId=rebateTypeMap[row['采购折让类型']]
          policyForm.other.hnyyRebateTypeIdName=row['采购折让类型']
          console.log("row['折让计算期间']====>",row['折让计算期间'])
          policyForm.hnyyRebateModueId=rebatePeriodTypeMap[row['折让计算期间']]
          policyForm.other.hnyyRebateModueIdName=row['折让计算期间']
          policyForm.purPrice=row['进价']
          policyForm.purRate=row['采购折让比率']
          policyForm.purRebatePrice=row['采购折让单价']
          policyForm.venderId=policyForm.venderPartyId
          policyForm.zbPrice=row['中标价']
          policyForm.clientId=row['客户名称']
          policyForm.sysClientPriceSetsList=row['客户集合']
          policyForm.purRebatePrice=row['采购折让单价']
          policyForm.payDay=row['付款账期（天数）']
          policyForm.venderId=row['供应商编码']
          console.log('policyForm',policyForm)
          // 提交数据
          await request.post('/link/addTem', policyForm).then((res)=>{
            if (res.code === 200) {
              ElMessage.success('提交成功')
              console.log('res',res)
              load()
            } else {
              ElMessage.error(res.msg || '提交失败')
            }
          })
        }

      })

    } catch (err) {
      console.error('提交失败', err)
    }
  }
  }

  reader.readAsBinaryString(file)
  return false
}




// 政策类型Map
const policyTypeMap={
  '采购折让': '1',
  '销售折让': '2',
  '二次扣点': '3'
}

// 取值来源类型Map
const sourceTypeMap={
  '销售流向': '1',
  '购进流向': '2',
}

// 折让计算期间类型Map
const rebatePeriodTypeMap={
  '月度': '1',
  '季度': '2',
  '半年度': '3',
  '年度': '4'
}
// 折让方式类型Map
const rebateMethodTypeMap={
  '票扣': '1',
  '红票': '2',
  '现金': '3'
}

// 采购折让类型类型Map
const rebateTypeMap={
  '付款折让': '1',
  '已销定返': '2',
  '总量折让': '3',
  '税率补偿': '4',
  '扫码补偿': '5',
  '二次销售': '6'
}

// 获取唯一商品数据参数
const importSearch=ref({
  venderName:'',
  goodsName:''
})
// 提交数据
const submitData = async () => {
  if (!tableDataList.value.list.length) {
    return ElMessage.warning('请先导入文件')
  }
  console.log('tableDataList.value',tableDataList.value)
  for (const row of tableDataList.value.list) {
    try {
      console.log('row',row)
          // 提交数据
          await request.post('/link/addPolicy', row).then(async (res)=>{
            if (res.code === 200) {
              ElMessage.success('提交成功')
              console.log('res',res)

              // 更改临时表状态
              await request.get('/link/updateTem', { params: { id: row.hnyyTemId, opFlag: 1 } }).then((res)=>{
                if (res.code === 200) {
                  ElMessage.success('状态更新成功')
                  load()
                } else {
                  ElMessage.error(res.msg || '状态更新失败')
                }
              })
            } else {
              ElMessage.error(res.msg || '提交失败')
            }
          })
    } catch (err) {
      console.error('提交失败', err)
    }
  }
}

// 存储数据
const tableDataList = ref({
  list: [],
  total: 0,
  pageNum: 1,
  pageSize: 20,
})
// 获取临时表数据
const load=()=>{
  request.get('/link/getTem', { params: { pageNum: tableDataList.value.pageNum, pageSize: tableDataList.value.pageSize } }).then((res)=>{
    if(res.code===200){
      tableDataList.value.list=res.data.list
      tableDataList.value.total=res.data.total
    }else{
      ElMessage.error(res.msg || '获取临时表数据失败')
    }
  })
}
load()

const deleteRow=(row)=>{
  console.log('row',row)
  console.log('row',row.hnyyTemId)
  request.get('/link/updateTem', { params: { id: row.hnyyTemId, opFlag: 2 } }).then((res)=>{
    if (res.code === 200) {
      ElMessage.success('删除成功')
      load()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  })
}
</script>



<style>

</style>
